//
//  M1ResponsDecryption.m
//  NewMarryU
//
//  Created by apple on 2018/7/16.
//  Copyright © 2018年 Cedar. All rights reserved.
//

#import "M1ResponsDecryption.h"
#import "M1HttpConfig.h"
@implementation M1ResponsDecryption
-(id)initWithResponse:(NSHTTPURLResponse *)response data:(NSData *)data{
    self = [super init];
    if (self) {
        _desData = data;
        NSDictionary *all_fields = response.allHeaderFields;
        NSString *m1_conten_type = all_fields[@"Content-Type"];
        NSString *en1 = all_fields[@"MarryU-Encrypt"];
        NSString *en2 = all_fields[@"marryu-encrypt"];
        
        if (([m1_conten_type rangeOfString:@"application/json"].location != NSNotFound ||
             [m1_conten_type rangeOfString:@"text/json"].location != NSNotFound ||
             [m1_conten_type rangeOfString:@"text/html"].location != NSNotFound ||
             [m1_conten_type rangeOfString:@"text/javascript"].location != NSNotFound ||
             [m1_conten_type rangeOfString:@"application/javascript"].location != NSNotFound) && ([en1 isEqualToString:@"1"]||[en2 isEqualToString:@"1"]))
        {
            _is_valid = YES;
        }
        
        if (_is_valid) {
            NSString *_encoding = nil;
            NSArray *_com = [m1_conten_type componentsSeparatedByString:@"charset="];
            if (_com.count >2) {
                _encoding = [[_com lastObject] lowercaseString];
            }else{
                _encoding = @"utf-8";
            }
            
            CFStringEncoding _encString = [self _cfEncoding:_encoding];
            
            if ((long)_encString > -1 && data.length >0) {
                
                NSString *_h_string = [[NSString alloc]initWithData:data encoding:CFStringConvertEncodingToNSStringEncoding(_encString)];
                
                NSData *_unHData = [self _dataByRemoveHs:_h_string];
                
                NSData *_unDesData = [self _unDesDataWith:_unHData oper:kCCDecrypt options:kCCOptionECBMode | kCCOptionPKCS7Padding signkey:[m1_response_sign dataUsingEncoding:NSUTF8StringEncoding]];
                
                _desData = [NSJSONSerialization JSONObjectWithData:_unDesData options:NSJSONReadingAllowFragments error:nil];
            }
        }
    }
    return self;
}

-(NSData *)_unDesDataWith:(NSData *)data oper:(CCOperation)oper options:(CCOptions)options signkey:(NSData *)key {
    size_t bufferSize = (data.length + kCCBlockSize3DES) & ~(kCCBlockSize3DES - 1);
    
    uint8_t *buffer = malloc(bufferSize * sizeof(uint8_t));
    
    memset(buffer, 0x0, bufferSize);
    
    size_t dataNumber = 0;
    
    NSData *_undesdata = nil;
    
    if (CCCrypt(oper, kCCAlgorithm3DES, options, key.bytes, kCCKeySize3DES, 0, data.bytes, data.length, buffer, bufferSize, &dataNumber) == kCCSuccess)
    {
        _undesdata = [NSData dataWithBytes:buffer length:dataNumber];
    }
    
    return _undesdata;
}

-(NSData *)_dataByRemoveHs:(NSString *)_h_string{
    if (_h_string.length % 2 > 0)
    {
        return nil;
    }
    
    unsigned char *buffer = malloc(_h_string.length / 2);
    
    for (NSUInteger i = 0; i < _h_string.length / 2; i ++)
    {
        buffer[i] = strtol([[_h_string substringWithRange:NSMakeRange(2 * i, 2)] UTF8String], NULL, 16);
    }
    
    NSData *data = [NSData dataWithBytes:buffer length:_h_string.length / 2];
    
    free(buffer);
    
    return data;
}

-(CFStringEncoding )_cfEncoding:(NSString *)encoding{
    if ([encoding isEqualToString:@"utf-8"] || [encoding isEqualToString:@"utf8"])
    {
        return kCFStringEncodingUTF8;
    }
    else if ([encoding isEqualToString:@"utf-16"] || [encoding isEqualToString:@"utf16"])
    {
        return  kCFStringEncodingUTF16;
    }
    else if ([encoding isEqualToString:@"utf-16le"] || [encoding isEqualToString:@"utf16le"])
    {
        return  kCFStringEncodingUTF16LE;
    }
    else if ([encoding isEqualToString:@"utf-16be"] || [encoding isEqualToString:@"utf16be"])
    {
        return  kCFStringEncodingUTF16BE;
    }
    else if ([encoding isEqualToString:@"utf-32"] || [encoding isEqualToString:@"utf32"])
    {
        return  kCFStringEncodingUTF32;
    }
    else if ([encoding isEqualToString:@"utf-32le"] || [encoding isEqualToString:@"utf32le"])
    {
        return  kCFStringEncodingUTF32LE;
    }
    else if ([encoding isEqualToString:@"utf-32be"] || [encoding isEqualToString:@"utf32be"])
    {
        return  kCFStringEncodingUTF32BE;
    }
    return -1;
}

@end
